﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace RAP.Framework.Libary.SqlTaskParser
{
	/// <summary>
	/// Sql解析结果
	/// </summary>
	public class SqlParseResult : IDisposable
	{
		/// <summary>
		/// 
		/// </summary>
		public SqlParseResult( )
		{
		}

		/// <summary>
		/// 查询任务集合
		/// </summary>
		public IList<SqlTaskCollection> SqlTasks { get; set; } = new List<SqlTaskCollection>();

		/// <summary>
		/// SQL语句中的所有Token
		/// </summary>
		public IList<SqlToken> Tokens { get; set; } = new List<SqlToken>();

		/// <summary>
		/// 结果集别名集合
		/// </summary>
		public HashSet<string> ResultAlias { get; set; }

		/// <summary>
		/// 创建模型的函数[Handler]
		/// </summary>
		public Func<string, IDictionary, object> CreateDataModel { get; set; }

		/// <summary>
		/// 从所有的SqlTask中查找指定resultName名称的结果集
		/// </summary>
		/// <param name="resultName"></param>
		/// <returns></returns>
		public object FindResultByName( string resultName )
		{
			foreach ( var sqlTasks in SqlTasks )
			{
				foreach ( var task in sqlTasks )
				{
					if ( task.Reuslt.Contains( resultName ) )
					{
						return task.Reuslt[ resultName ];
					}
				}
			}
			return null;
		}

		/// <summary>
		/// 释放资源
		/// </summary>
		public void Dispose( )
		{
			SqlTasks?.All( tasks =>
			{
				tasks?.All( task =>
				{
					task?.Dispose();
					return true;
				} );
				return true;
			} );
			SqlTasks?.Clear();
			SqlTasks = null;

			Tokens?.Clear();
			Tokens = null;
		}
	}
}
